# get_pachube_data.py
''' Read the data that the USCG monitor is sending to Pachube and write it to
    /var/www/readings.json as if it were being put there by get_readings.py
    '''
# 8/19/10 TS-7500 runs Python 2.5.2 and thus need this:
from __future__ import with_statement

import urllib, time, traceback
import simplejson as json
import mac, credentials
URL = 'http://api.pachube.com/v2/feeds/9081.json?key='
run = True
READINGS = '/var/www/readings.json'
#READINGS = 'readings.json'
watts = [0.0]*24

while run:
    ok = True
    try:
        f = urllib.urlopen(URL+credentials.pachube_key())
    except:
        print 'error opening ',URL
        traceback.print_exc()
        ok = False
    if ok:
        try:
            s = f.read()
        except:
            print 'error reading ', URL
            traceback.print_exc()
            f.close()
            ok = False
    if ok:
        f.close()
        # print s
        try:
            j = json.loads(s)
        except:
            print 'json error: ', URL
            traceback.print_exc()
            ok = False
    if ok:
        jout = {}
        jout[u'mac'] = mac.getMacAddress()
        try:
            datastreams = j[u'datastreams'][1:]
        except:
            print "datastreams = j[u'datastreams][1:] error", s
            traceback.print_exc()
            ok = False
    if ok:
        for datastream in datastreams:
            id = int(datastream[u'id'])-1 
            watts[id] = float(datastream[u'current_value'])
            #print datastream[u'current_value']
        jout[u'watts'] = watts
        jout[u'datetime'] = time.ctime()
        s = json.dumps(jout)
        # print s
        with open(READINGS, 'w') as f:
            f.write(s)
    time.sleep(60)
    # run = False
